/*
 * EK.Eventable: A prototype for adding custom events to an object
 * Inspired by jQuery Events API
 * 
 * Enrichment Kit @ek.version@ (http://enrichmentkit.com)
 * Copyright (c) 2008 Pink Hominid
 * Licensed under terms of the MIT License (LICENSE.txt)
 * 
 * IE 6.0+, FF 1.5+ Tested
 */
EK.Eventable = function EkEventable() {
    var observers = {};
	var batchTypes = [];

	this.startBatchNotification = function (type) {
		if (EK.arrayIndexOf(batchTypes, type) === -1) {
			batchTypes.push(type);
		}
	};

	this.endBatchNotification = function (type, data) {
		var idx = EK.arrayIndexOf(batchTypes, type);
		var that = this;
		if (idx > -1) {
			setTimeout(function() {
				batchTypes.splice(idx, 1);
				that.trigger(type, data);
			}, 10);
		}
	};

    this.trigger = function (type, data) {
		if (EK.arrayIndexOf(batchTypes, type) === -1) {
			var observersOfType = observers[type];
			if (observersOfType) {
				for (var i = 0; i < observersOfType.length; i++) {
					observersOfType[i](type, data);
				}
			}
		}
    };
    
    this.bind = function (type, fn) {
        var observersOfType = observers[type];
        if (observersOfType) {
            observersOfType.push(fn);
        } else {
            observers[type] = [fn];
        }
    };
    
    this.unbind = function (type, fn) {
		if (arguments.length === 0) { // unbind all
            observers = {};
		} else {
	        var observersOfType = observers[type];
	        if (observersOfType) {
	            if (arguments.length > 1) {
	                var startLength = observersOfType.length;
	                for (var i = startLength - 1; i >= 0; i--) {
	                    if (observersOfType[i] === fn) {
	                        observersOfType.splice(i, 1);
	                    }
	                }
	            } else { // unbind all of type
	                observersOfType = null;
	            }
	        }
		}		
    };
};
